package com.sky.controller.user;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sky.entity.Dish;
import com.sky.mapper.DishMapper;
import com.sky.result.Result;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * @Version: 1.0
 * @author: wanglonghui
 * @date: 2025/10/13 17:40
 * @description:
 */

@RestController("userDishController")
@RequestMapping("/user/dish")
@Slf4j
@Api(tags = "C端-菜品浏览接口")
public class DishController {


    @Autowired
    private RedisTemplate<String, Object> redisTemplate;


    @Autowired
    private DishService dishService;

    @Autowired
    private DishMapper dishMapper;

    @GetMapping("/list")
    @ApiOperation("根据分类id获取菜品列表")
    public Result<List<DishVO>> getDishList(@PathVariable Long categoryId) {
        // 构造redis中的key,规则: dish_分类id
        String dishKey = "dish_" + categoryId;

        //查询redis中是否存在菜品数据
        List<DishVO> dishVOS = (List<DishVO>) redisTemplate.opsForValue().get(dishKey);
        if(!CollectionUtils.isEmpty(dishVOS)){
            // 存在, 直接返回，无需查数据库。
            return Result.success(dishVOS);
        }
        // 不存在，查询数据库
        Dish dish = new Dish();
        dish.setCategoryId(categoryId);
        dish.setStatus(1);
        // todo：查询起售中的菜品. 查询数据库有误，待后续核对
        dishVOS = dishService.savaWithFlavor(dish);
//        LambdaQueryWrapper<Dish> lambdaQueryWrapper = new LambdaQueryWrapper<>();
//        lambdaQueryWrapper.eq(Dish::getCategoryId, categoryId);
//        lambdaQueryWrapper.eq(Dish::getStatus, 1);
//        List<Dish> list = dishService.list(lambdaQueryWrapper);
//        BeanUtils.copyProperties(list, dishVOS);
        // 设置到缓存中
        redisTemplate.opsForValue().set(dishKey, dishVOS);
        return Result.success(dishVOS);

    }

}
